package com.tadpole.music.view.fragment.me;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tadpole.music.R;
import com.tadpole.music.adapter.base.BaseAdapter;
import com.tadpole.music.adapter.study.AnswerStatisticsAdapter;
import com.tadpole.music.bean.question.QuestionRankBean;
import com.tadpole.music.bean.question.UniversityBean;
import com.tadpole.music.bean.study.MyExamsFootBean;
import com.tadpole.music.bean.study.MyExamsHeadBean;
import com.tadpole.music.bean.study.QuestionCountHeadBean;
import com.tadpole.music.config.Constant;

import com.tadpole.music.iView.question.QuestionRankIView;
import com.tadpole.music.iView.question.UniversityIView;
import com.tadpole.music.iView.study.MyExamsIView;
import com.tadpole.music.iView.study.QuestionCountIView;
import com.tadpole.music.presenter.me.ShiZhanStudentPresenter;

import com.tadpole.music.presenter.question.QuestionRankPresenter;
import com.tadpole.music.presenter.question.UniversityPresenter;
import com.tadpole.music.presenter.study.QuestionCountPresenter;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.activity.study.ErrorExamActivity;
import com.tadpole.music.view.activity.study.ExaminationErrorActivity;
import com.tadpole.music.view.event.StudentRefreshEvent;
import com.tadpole.music.view.fragment.base.BaseFragment;
import com.tadpole.music.view.widget.NiceImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 学生实战真题
 * Created By 孙岩
 * on 2020/9/30
 */
public class StudentShiZhanFragment extends BaseFragment implements UniversityIView , QuestionRankIView,QuestionCountIView , MyExamsIView {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    //学生id
    private String mParam1;
    private String mParam2;
    private String mParam3;
    //刷新
    private SmartRefreshLayout rl_refresh;
    //头像
    private NiceImageView ivImage;
    //学院名称
    private TextView  tvName;
    //正确率
    private TextView tvAccuracy;
    //答题时长
    private TextView tvAnswerTime;
    private RecyclerView recyclerView;
    private AnswerStatisticsAdapter answerStatisticsAdapter;
    //获取学院的presenter
    private UniversityPresenter universityPresenter;
    //获取等级的presenter
    private QuestionRankPresenter questionRankPresenter;
    //实战真题头部
    private QuestionCountPresenter questionCountPresenter;
    //实战真题尾部
    private ShiZhanStudentPresenter shiZhanStudentPresenter;

    //学院id
    private String college_id;
    //学院名称
    private String college_name;
    //等级id
    private String rank_id;

    public static StudentShiZhanFragment newInstance(String param1, String param2,String param3) {
        StudentShiZhanFragment fragment = new StudentShiZhanFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, param3);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_student_shizhan;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            mParam3 = getArguments().getString(ARG_PARAM3);
        }
    }

    @Override
    protected void initView(View mRootView) {
        //注册
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        ivImage = mRootView.findViewById(R.id.ivImage);
        rl_refresh = mRootView.findViewById(R.id.rl_refresh);
        tvName = mRootView.findViewById(R.id.tvName);
        tvAccuracy = mRootView.findViewById(R.id.tvAccuracy);
        recyclerView = mRootView.findViewById(R.id.recyclerView);
        tvAnswerTime = mRootView.findViewById(R.id.tvAnswerTime);

        //获取学院
        universityPresenter = new UniversityPresenter();
        universityPresenter.attachView(this);
        universityPresenter.getUniversity();
        //获取等级
        questionRankPresenter = new QuestionRankPresenter();
        questionRankPresenter.attachView(this);
        //实战真题头部
        questionCountPresenter = new QuestionCountPresenter();
        questionCountPresenter.attachView(this);
        //实战真题尾部
        shiZhanStudentPresenter = new ShiZhanStudentPresenter();
        shiZhanStudentPresenter.attachView(this);

        rl_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                questionCountPresenter.getQuestionCountHeadStudent(college_name,college_id,rank_id , "2",mParam1);
                shiZhanStudentPresenter.getExamsFoot(college_id,mParam1, true);
            }
        });

        rl_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                shiZhanStudentPresenter.getExamsFootMore(college_id,mParam1);
            }
        });

    }

    //学院回调
    @Override
    public void showUniversity(List<UniversityBean.DataBean> list) {
        if(list!=null&&list.size()!=0){
            college_id = String.valueOf(list.get(0).getId());
            college_name = String.valueOf(list.get(0).getName());
            questionRankPresenter.getQuestionRank(list.get(0).getId());
        }
    }

    //等级回调
    @Override
    public void showQuestionRank(List<QuestionRankBean.DataBean> list) {
        if(list!=null&&list.size()!=0){
            rank_id = String.valueOf(list.get(0).getId());
            //获取头部
            questionCountPresenter.getQuestionCountHeadStudent(college_name,college_id,rank_id , "2",mParam1);
            //获取尾部
            shiZhanStudentPresenter.getExamsFoot(college_id,mParam1, false);
        }
    }

    @Override
    public void showQuestionCount(QuestionCountHeadBean.DataBean bean, String college_name, String class_name) {
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.app_icon)
                .error(R.mipmap.app_icon)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);

        if (mParam2.equals("")) {
            Glide.with(Objects.requireNonNull(this)).load(R.mipmap.app_icon).apply(requestOptions).into(ivImage);
        } else {
            Glide.with(Objects.requireNonNull(this)).load(mParam2).apply(requestOptions).into(ivImage);
        }

        tvName.setText(college_name);

        if (bean.getRate().equals("NaN")) {
            tvAccuracy.setText("0");
        } else {
            tvAccuracy.setText((new BigDecimal(Double.parseDouble(bean.getRate()) * 100).setScale(2, BigDecimal.ROUND_UP).doubleValue())+"");
        }

        if (bean.getTime().equals("NaN")) {
            tvAnswerTime.setText("0");
        } else {
            tvAnswerTime.setText(bean.getTime());
        }
    }

    @Override
    public void showExamsHead(MyExamsHeadBean.DataBean bean) {

    }

    @Override
    public void showExamsFoot(final List<MyExamsFootBean.DataBeanX.DataBean> list) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        //创建适配器
        answerStatisticsAdapter = new AnswerStatisticsAdapter(getActivity(), list,1);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(answerStatisticsAdapter);

        answerStatisticsAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if(Mutils.isNetworkAvailable()){
                    Intent intent = new Intent(getActivity(), ErrorExamActivity.class);
                    intent.putExtra("id",list.get(position).getId());
                    intent.putExtra("flag","2");
                    intent.putExtra("student_id",mParam1);
                    startActivity(intent);
                }else{
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void notifyAdapter() {
        answerStatisticsAdapter.notifyDataSetChanged();
    }

    @Override
    public void stopRefresh() {
        rl_refresh.finishRefresh();
        rl_refresh.finishLoadMore();
    }

    @Override
    public void show401() {
        SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "");
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onComment(StudentRefreshEvent event) {
        college_id = event.getCollege_id();
        rank_id = event.getRank_id();
        college_name = event.getCollege_name();
        questionCountPresenter.getQuestionCountHeadStudent(event.getCollege_name(),event.getCollege_id(),event.getRank_id() , "2",mParam1);
        shiZhanStudentPresenter.getExamsFoot(event.getCollege_id(),mParam1, true);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //注册
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
